<script setup lang="ts">
import { deleteMemberOrderAPI, getOrderListAPI, getPayMockAPI, getPayWxPayMiniPayAPI } from '@/api/order';
import type { OrderItem, OrderListParams } from '@/types/order';
import { orderStateList, OrderState } from '@/types/constants';
import { onMounted } from 'vue';
import { ref } from 'vue';


// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 获取订单列表页（父）传到订单列表内容组件（子）的传参
const props = defineProps<{
        orderState: number
}>()
// 接口请求参数定义
const queryParams: Required<OrderListParams>={
        page: 1,
        pageSize: 5,
        orderState: props.orderState
}
// 定义页面是否还有更多数据
const finish = ref(false)
// 获取订单列表
const orderList = ref<OrderItem[]>([])
const getOrderListData = async ()=>{
        if(finish.value === true){
          uni.showToast({icon: 'none', title: '没有更多数据了...'})
          return
        }
        const res = await getOrderListAPI(queryParams)
        orderList.value.push(...res.result.items)
        // 当前页小于接口数据总页数，即还能继续加载数据
        if(queryParams.page < res.result.pages){
          queryParams.page++
        }else{
          finish.value = true
        }
}

// 列表滑动到底部触底事件
const onScrollToLower = async () =>{
  await getOrderListData()
}
// 去支付
const handlePay = async (id:string)=>{
  if(import.meta.env.DEV){
    // 开发环境，模拟支付
    await getPayMockAPI({orderId: id})
  }else{
    // 正式环境微信支付
    const res = await getPayWxPayMiniPayAPI({orderId: id})
  }
  // 支付成功后跳转无返回按钮的“支付成功页”
  uni.redirectTo({url: `/pagesOrder/payment/payment?id=${id}`})
}
const resetData = () => {
  // 重置页码
  queryParams.page = 1
  // 重置列表
  orderList.value = []
  // 重置结束标记
  finish.value = false
}
  // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
  const triggered = ref(false)
  // scroll-view下拉事件
  const onRefresherrefresh = async ()=>{
    console.log('下拉')
    //下拉动画开启
    triggered.value = true
    resetData()
    await getOrderListData()
    //下拉动画关闭
    triggered.value = false
  }
  // 删除订单
const deleteOrder =(id:string)=>{
  uni.showModal({
    title: '提示',
    content: '是否删除订单？',
    showCancel: true,
    cancelText: '取消',
    cancelColor: '#000000',
    confirmText: '确定',
    confirmColor: '#3CC51F',
    success: async (result) => {
      if(result.confirm){
        await deleteMemberOrderAPI({ids: [id]})
        // 将页码置回初始值，并重新加载数据
        resetData()
        await getOrderListData()
        // uni.redirectTo({
        //   url:'/pagesOrder/list/list',
        // })
      }
    },
    fail: ()=>{},
    complete: ()=>{}
  });
}
// 组件挂载时执行
onMounted(()=>{
        getOrderListData()
})
</script>

<template>
  <!-- 订单列表 -->
  <scroll-view scroll-y class="orders" refresher-enabled @scrolltolower="onScrollToLower" @refresherrefresh="onRefresherrefresh" :refresher-triggered="triggered">
          <view class="card" v-for="item in orderList" :key="item.id">
            <!-- 订单信息 -->
            <view class="status">
              <text class="date">{{item.createTime}}</text>
              <!-- 订单状态文字 -->
              <text>{{orderStateList[item.orderState].text}}</text>
              <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
              <text class="icon-delete" v-if="item.orderState >= OrderState.DaiPingJia" @tap="deleteOrder(item.id)"></text>
            </view>
            <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
            <navigator
              v-for="sku in item.skus"
              :key="sku.id"
              class="goods"
              :url="`/pagesOrder/detail/detail?id=${item.id}`"
              hover-class="none"
            >
              <view class="cover">
                <image
                style="width: 100%;height: 100%;"
                  mode="aspectFit"
                  :src="sku.image"
                ></image>
              </view>
              <view class="meta">
                <view class="name ellipsis">{{sku.name}}</view>
                <view class="typeAndSku">
                  <view class="type">{{sku.attrsText}}</view>
                  <view class="skuClass">￥{{sku.curPrice}}  ×{{ sku.quantity }}</view>
                </view>
              </view>
            </navigator>
            <!-- 支付信息 -->
            <view class="payment">
              <text class="quantity">共{{item.totalNum}}件商品</text>
              <text>实付</text>
              <text class="amount"> <text class="symbol">¥</text>{{item.totalMoney}}</text>
            </view>
            <!-- 订单操作按钮 -->
            <view class="action">
              <!-- 待付款状态：显示去支付按钮 -->
              <template v-if="item.orderState === OrderState.DaiFuKuan">
                <view class="button primary" @tap="handlePay(item.id)">去支付</view>
              </template>
              <template v-else>
                <navigator
                  class="button secondary"
                  :url="`/pagesOrder/create/create?orderId=${item.id}`"
                  hover-class="none"
                >
                  再次购买
                </navigator>
                <!-- 待收货状态: 展示确认收货 -->
                <view v-if="item.orderState === OrderState.DaiShouHuo" class="button primary">确认收货</view>
              </template>
            </view>
          </view>
          <!-- 底部提示文字 -->
          <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
            {{ finish ? '没有更多数据~' : '正在加载...' }}
          </view>
        </scroll-view>
</template>

<style lang="scss">
// 订单列表
.orders {
        height: 100%;
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    .typeAndSku {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }
    .skuClass {
      margin-top: 10rpx;
      font-size: 26rpx;
      color: #444;
    }
    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
      width: 50%;
      max-height: 80rpx;
      overflow: hidden;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #db1818;
      border-color: #db1818;
    }

    .primary {
      color: #fff;
      background-color: #db1818;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>